package org.abacus.hibernate.mandarinduck;

import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author chaoyang.li
 */
public class HibernateTransactionStrategy extends org.abacus.hibernate.HibernateTransactionStrategy implements TransactionStrategy {
	private static final ThreadLocal<TransactionStrategy> instance = new ThreadLocal<TransactionStrategy>();
	private Transaction txIn;
	private Transaction txOut;

	/**
	 * @author chaoyang.li
	 */
	private HibernateTransactionStrategy() {
		super();
	}

	/**
	 * @author chaoyang.li
	 */
	public static TransactionStrategy getInstance() {
		if (instance.get() == null) {
			instance.set(new HibernateTransactionStrategy());
		}
		return instance.get();
	}

	/**
	 * @author chaoyang.li
	 */
	public void beginIn() {
		try {
			Session session = HibernateSessionProvider.getCurrentSessionIn();
			txIn = begin(session);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @author chaoyang.li
	 */
	public void commitIn() {
		commit(txIn);
	}

	/**
	 * @author chaoyang.li
	 */
	public void rollbackIn() {
		rollback(txIn);
	}

	/**
	 * @author chaoyang.li
	 */
	public void clearCacheIn() {
		Session session = HibernateSessionProvider.getCurrentSessionIn();
		clearCache(session);
	}

	/**
	 * @author chaoyang.li
	 */
	public void beginOut() {
		try {
			Session session = HibernateSessionProvider.getCurrentSessionOut();
			txOut = begin(session);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void commitOut() {
		commit(txOut);
	}

	/**
	 * @author chaoyang.li
	 */
	public void rollbackOut() {
		rollback(txOut);
	}

	/**
	 * @author chaoyang.li
	 */
	public void clearCacheOut() {
		Session session = HibernateSessionProvider.getCurrentSessionOut();
		clearCache(session);
	}

}
